/*
 * Copyright (C) 2008 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.sav.metronome;

import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import java.util.Timer;
import java.util.TimerTask;

public class Metronome extends Activity {

  private static final int MIN_PERIOD = 1;
  private static final int MAX_PERIOD = 900;
  private static final int INITIAL_PERIOD = 80;
  private Timer timer = null;
  private int period = INITIAL_PERIOD;
  private MediaPlayer player;
  private Button toggleButton;
  private boolean running = false;
  private static final String TAG = "Metronome";
  private AudioManager audioManager;

  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

    player = MediaPlayer.create(this, R.raw.sticks);
    player.setAudioStreamType(AudioManager.STREAM_MUSIC);
    
    EditText text = (EditText) findViewById(R.id.timepicker_input);
    text.setEnabled(false);

    NumberPicker picker = (NumberPicker) findViewById(R.id.picker);
    picker.setRange(MIN_PERIOD, MAX_PERIOD);
    picker.setCurrent(period);
    picker.setOnChangeListener(new NumberPicker.OnChangedListener() {

      public void onChanged(NumberPicker picker, int oldVal, int newVal) {
        period = picker.getCurrent();
        Log.d(TAG, Integer.toString(period));
        if (running)
          startTimer();
      }
    });

    toggleButton = (Button) findViewById(R.id.toggle);
    toggleButton.setText(R.string.btn_stop);

    toggleButton.setOnClickListener(new OnClickListener() {

      public void onClick(View arg0) {
        toggleTimer();
        running = !running;
      }
    });

  }

  @Override
  public boolean onKeyDown(int keyCode, KeyEvent event) {
    switch (keyCode) {
      case KeyEvent.KEYCODE_VOLUME_UP:
        Log.d(TAG, "Volume up");
        audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,
                AudioManager.ADJUST_RAISE, AudioManager.FLAG_PLAY_SOUND);
        break;
      case KeyEvent.KEYCODE_VOLUME_DOWN:
        Log.d(TAG, "Volume down");
        audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,
                AudioManager.ADJUST_LOWER, AudioManager.FLAG_PLAY_SOUND);
        break;
    }

    return super.onKeyDown(keyCode, event);
  }

  private void toggleTimer() {
    if (timer != null)
      stopTimer();
    else
      startTimer();
  }

  private void stopTimer() {
    if (timer != null) {
      Log.d(TAG, "Stop running timer");
      timer.cancel();
      timer.purge();
      timer = null;
      toggleButton.setText(R.string.btn_stop);
    }
  }

  private void startTimer() {
    if (timer != null)
      stopTimer();
    Log.d(TAG, "Start timer with period: " + period);
    toggleButton.setText(R.string.btn_run);
    timer = new Timer();
    timer.schedule(new TimerTask() {

      @Override
      public void run() {
        player.start();
        Log.d(TAG, "Tick");
      }
    }, 0, 60000 / period);
  }

  @Override
  public void finish() {
    Log.d(TAG, "finish");
    player.release();
    player = null;
    super.finish();
  }

  @Override
  protected void onPause() {
    Log.d(TAG, "pause");
    stopTimer();
    super.onPause();
  }
}
